﻿import { finalize } from 'rxjs/operators';
import { Component, OnInit, Injector } from '@angular/core';
import {
    ArticleEditDto,
    ArticleServiceProxy,
    CreateOrUpdateArticleInput
} from '@shared/service-proxies/service-proxies';

import { NzDrawerRef } from 'ng-zorro-antd';
import { AppComponentBase } from '@shared/common/app-component-base';

/*富文本编辑器 */
import * as ClassicEditor from '@ckeditor/ckeditor5-build-classic';
import '@ckeditor/ckeditor5-build-classic/build/translations/zh-cn.js';

@Component({
    selector: 'createOrEditArticleModal',
    templateUrl: './create-or-edit-article-modal.component.html',
    styles: [
        `
        .footer {
          position: absolute;
          bottom: 0px;
          width: 100%;
          border-top: 1px solid rgb(232, 232, 232);
          padding: 10px 16px;
          text-align: right;
          left: 0px;
          background: #fff;
        }
      `
    ],
})
export class CreateOrEditArticleModalComponent extends AppComponentBase implements OnInit {
    public Editor = ClassicEditor;
    // 配置语言
    public config = {
        language: 'zh-cn'
    };
    articleId?: number;
    article: ArticleEditDto = new ArticleEditDto();
    saving = false;

    constructor(injector: Injector, private _articleService: ArticleServiceProxy, private drawerRef: NzDrawerRef<number>) {
        super(injector);
    }

    ngOnInit() {
        this.init();
    }

    init(): void {
        const self = this;

        self._articleService.getArticleForEdit(self.articleId).subscribe(result => {
            self.article = result.article;
        });
    }

    save(): void {
        const input: CreateOrUpdateArticleInput = new CreateOrUpdateArticleInput();
        input.article = this.article;
        this.saving = true;
        this._articleService
            .createOrUpdateArticle(input)
            .pipe(finalize(() => (this.saving = false)))
            .subscribe(() => {
                this.notify.success(this.l('SavedSuccessfully'));
                this.drawerRef.close(1);
            });
    }

    close(): void {
        this.drawerRef.close(0);
    }
}
